// 封装iframe 发送及接受Token的方法
// useSyncToken不知道有啥用
import { SYNCHRONIZATION_TOKEN } from "@/constant";
import { useUserStore } from "@/store/modules/user";
import { getStorageByKey, localSave, localGetApplicationId } from "@/utils/common";

export const sendToken = (iframeRef: HTMLIFrameElement) => {
  const appUser = localGetApplicationId("app-user-store") || getStorageByKey("app-user-store");
  const userInfo = localGetApplicationId("al__USER_INFO") || getStorageByKey("al__USER_INFO");

  const message = {
    from: import.meta.env.VITE_APP_ID,
    type: SYNCHRONIZATION_TOKEN,
    appId: {
      value: appUser.appid,
      expire: userInfo.expire,
    },
    uid: {
      value: appUser.uuid,
      expire: userInfo.expire,
    },
    productId: {
      value: appUser.productId,
      expire: userInfo.expire,
    },
    tenantId: {
      value: appUser.tenantId,
      expire: userInfo.expire,
    },
    token: {
      value: appUser.token,
      expire: userInfo.expire,
    },
    userInfo: userInfo,
  };

  iframeRef.contentWindow?.postMessage(message, "*");
};

export const getToken = (data) => {
  // 屏蔽自身发送的信息
  if (data.type !== SYNCHRONIZATION_TOKEN || data.from === import.meta.env.VITE_APP_ID) {
    return;
  }

  const userStore = useUserStore();
  const { appId, productId, token, uid, tenantId, userInfo } = data;
  // 存储信息到pinia中
  userStore.setLoginInfo({
    token: token.value,
    uuid: uid.value,
    appid: appId.value,
    tenantId: tenantId.value,
    productId: productId.value,
  });
  userStore.setUserInfo(userInfo);

  // 存到localStorage
  localSave("al__Access-Token", token.value, token.expire);
  localSave("al__UID", uid.value, uid.expire);
  localSave("al__APPID", appId.value, appId.expire);
};
